package net.oschina.http;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

/**
 * Created by rex on 2015/3/10.
 */
public class Http {
    private String proxy = "";
    private HttpClient httpClient;

    /**
     * construction method with proxy
     * @param host
     * @param port
     * @throws IOException
     */
    public Http(String host, int port) throws IOException {
        this.httpClient = new DefaultHttpClient();
        this.SetProxy(host, port);
    }

    /**
     * construction method
     * @throws IOException
     */
    public Http() throws IOException {
        this.httpClient = new DefaultHttpClient();
    }

    /**
     * get method
     * @param url url
     * @return
     */
    public String Get(String url) {
        String body = "";
        try {
            HttpGet httpget = new HttpGet(url);
            HttpResponse httpresponse = this.httpClient.execute(httpget);
            HttpEntity entity = httpresponse.getEntity();
            body = EntityUtils.toString(entity);
            if (entity != null) {
                entity.consumeContent();
            }
        } catch (UnsupportedEncodingException e) {
            System.out.println("[W] Get Failed / UnsupportedEncodingException");
            return "";
        } catch (IOException e) {
            System.out.println("[W] Get Failed / IOException");
            return "";
        }

        return body;
    }

    /**
     * 设置代理
     * @param host
     * @param port
     * @throws IOException
     */
    public void SetProxy( String host, int port) throws IOException {
        this.proxy = host + port;
        HttpHost proxy = new HttpHost(host, port);
        this.httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy);
        System.out.println("[proxy] " + host + ":" + port);
    }
}
